# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QGridLayout, QVBoxLayout, QHBoxLayout
from qfluentwidgets import BodyLabel, setFont, TransparentToolButton, FluentIcon, ComboBox, ToolTipFilter, \
    VerticalSeparator

from .card import PluginCardWidget
from ...common import pluginManager, signalBus, cfg
from ...components import VerticalScrollArea


class PluginInterface(VerticalScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.view)
        self.horizontalLayout = QHBoxLayout()
        self.titleLabel = BodyLabel('插件管理', self.view)
        self.comboBox = ComboBox(self.view)
        self.grid = QGridLayout()
        self.cards = []

        self.initUI()
        self.register()

    def initUI(self):
        self.setObjectName("PluginInterface")
        self.setWidget(self.view)
        setFont(self.titleLabel, 20)

        self.comboBox.setPlaceholderText('主页插件')
        self.comboBox.setMaxVisibleItems(10)
        self.comboBox.currentTextChanged.connect(lambda: signalBus.homeChangedSignal.emit(self.comboBox.currentData()))

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.grid.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignTop)

        self.horizontalLayout.addStretch(1)
        self.horizontalLayout.addWidget(BodyLabel('主页插件：', self.view))
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout, 0)

        self.verticalLayout.addLayout(self.grid)
        self.grid.setColumnStretch(0, 1)
        self.grid.setColumnStretch(1, 1)

    def register(self):
        self.clear()
        plugins = pluginManager.values()

        for i, plugin in enumerate(plugins):
            card = PluginCardWidget(self)
            card.setPlugin(plugin)
            self.comboBox.addItem(plugin.name, plugin.icon, plugin)
            self.cards.append(card)
            self.grid.addWidget(card, i // 2, i % 2)

        it = cfg.get(cfg.homePlugin)
        self.comboBox.setCurrentText(it)

    def clear(self):
        for card in self.cards:
            self.grid.removeWidget(card)
            card.deleteLater()
        self.cards.clear()
        self.comboBox.clear()
